package com.web;

import com.Dao.UserMapper;
import com.pojo.User;
import com.utils.sqlSessionUtil;
import org.apache.ibatis.session.SqlSession;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;

public class UserServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doPost(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("utf-8");

        String action = request.getParameter("action");

        if ("sel".equals(action)){
           /* 获得页面提供信息*/
            String username = request.getParameter("userName");
            System.out.println(username+"################");
            SqlSession sqlSession = sqlSessionUtil.creatSqlSession();
            UserMapper useMapper = sqlSession.getMapper(UserMapper.class);

            List<User> all = useMapper.getAll();
            sqlSessionUtil.CloseSqlSession(sqlSession);
            if (all!=null){
               /* 从当前request获取session，若获取不到则自动创建，并且返回新创建的session；若获取到，则返回到获取到的session；*/
                HttpSession session = request.getSession();
               /* getAttribute() 方法返回指定属性名的属性值。*/
                //session.setAttribute("userName",username);
                session.setAttribute("list",all);
                response.sendRedirect("list.jsp");
            }else{
                PrintWriter out = response.getWriter();
                System.out.println("<script type=\"text/javascript\">\n" +
                        "    alert(\"暂时没有信息\");\n" +
                        "</script>");
                out.flush();
                out.close();
            }

        }else if ("del".equals(action)){
            String id=request.getParameter("id");
            SqlSession sqlSession = sqlSessionUtil.creatSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            int result = userMapper.delUser(Integer.parseInt(id));
            sqlSessionUtil.CloseSqlSession(sqlSession);
            response.sendRedirect("UserServlet?action=sel");
        }else if ("ins".equals(action)){
            String id=request.getParameter("id");
            SqlSession sqlSession = sqlSessionUtil.creatSqlSession();
            UserMapper userMapper = sqlSession.getMapper(UserMapper.class);

            int result = userMapper.insUser(Integer.parseInt(id));
            sqlSessionUtil.CloseSqlSession(sqlSession);
            response.sendRedirect("UserServlet?action=sel");
        }

    }
}
